﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.ComponentModel;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Vit.Common.Extensions;
using Vit.Web.Data;
using Vit.Web.Extensions;
using Vit.Web.Mvc.Results;
using Vit.Web.Services;

namespace Vit.Web.Mvc
{
    public class DataController<TContext, TEntity> : EntityRuleControllerBase<DataRule<TContext, TEntity>, TContext, TEntity>
        where TContext : DataContext, new()
        where TEntity : class, new()
    {
        public DataController()
            : this(DataRule<TContext, TEntity>.Create())
        {
        }

        public DataController(DataRule<TContext, TEntity> rule)
            : base(rule)
        {
        }

        protected override IQueryable<TEntity> QueryWithFilter(IQueryable<TEntity> query, object filterObj)
        {
            var md = rule.MetadataTypeAccessor.GetMetadataDescriptor(typeof(TEntity));
            FilteredMetadataTypeBase<TEntity> metadata = md.MetadataInstance as FilteredMetadataTypeBase<TEntity>;
            return metadata.QueryWithFilter(query, filterObj);
        }

        protected override TEntity GetEntityWithId(string id)
        {
            var md = rule.MetadataTypeAccessor.GetMetadataDescriptor(typeof(TEntity));
            MetadataTypeBase<TEntity> metadata = md.MetadataInstance as MetadataTypeBase<TEntity>;
            return metadata.GetEntityWithId(id);
        }

        protected override object CreateFilterObject()
        {
            var md = rule.MetadataTypeAccessor.GetMetadataDescriptor(typeof(TEntity));
            FilteredMetadataTypeBase<TEntity> metadata = md.MetadataInstance as FilteredMetadataTypeBase<TEntity>;
            return metadata.CreateFilterObject(this);
        }

        public bool TryUpdateFilter<TFilter>(TFilter obj) where TFilter : class
        {
            return base.TryUpdateModel<TFilter>(obj);
        }
    }
}
